package com.h2.ref.server.proxy;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProxyUtils {

   public static String normalizeUri(String path) {
      if(path == null) {
         return null;
      }
      int i = path.indexOf("*");
      if (i < 0)
         return path;
      if (i == 0)
         return "/";
      else
         return path.substring(0, i);
   }
   
   public static String combineUri(String leftStr, String rightStr) {
      if (rightStr == null || rightStr.length() <= 0) {
         return leftStr;
      }
      if (leftStr == null || leftStr.length() <= 0){
         return rightStr;
      }
      if ("/".equals(rightStr)) {
         return leftStr;
      }
      String s2 = rightStr;
      if (s2.charAt(0) == '/') {
         s2 = s2.substring(1);
      }
      if (s2.length() == 0) {
         return leftStr;
      }
      String s3 = "";
      String s4 = leftStr;
      int i = s4.indexOf("?");
      if (i > 0) {
         if (i < s4.length() - 1)
            s3 = s4.substring(i + 1);
         s4 = s4.substring(0, i);
      }
      
      if (!s4.endsWith("/")) {
         s4 = (new StringBuilder()).append(s4).append("/").toString();
      }
      s4 = (new StringBuilder()).append(s4).append(s2).toString();
      
      if (s3.length() > 0) {
         s4 = (new StringBuilder()).append(s4).append("?").append(s3)
         .toString();
      }
      return s4;
   }
   
   @SuppressWarnings("unchecked")
   public static Map<String, String> getHeaders(
         HttpServletRequest request) {

      Map<String, String> headers = new HashMap<String, String>();
      
      String name;
      String value;
      for (Enumeration<String> enumeration = request
            .getHeaderNames(); enumeration.hasMoreElements(); 
            headers.put(name, value)) {
         name = (String) enumeration.nextElement();
         value = "";
         for (Enumeration<String> enumeration1 = request
               .getHeaders(name); enumeration1.hasMoreElements();) {
            if (value.length() > 0) {
               value = (new StringBuilder()).append(value).append(",")
                     .toString();
            }
            value = (new StringBuilder()).append(value)
                  .append((String) enumeration1.nextElement()).toString();
         }
      }
      return headers;
   }
   
   public static String addQuery(String uri, String queryStr) {
      if(queryStr == null) {
         return uri;
      }
      StringBuilder builder = new StringBuilder(uri);
      if (uri.indexOf("?") < 0) {
         builder.append("?");
      }
      else {
         builder.append("&");
      }
      builder.append(queryStr);
      return builder.toString();
   }
   
   public static void setTimeout(Integer timeout) {
      if (timeout != null && timeout > 0) {
         Properties properties = System.getProperties();
         properties.put("sun.net.client.defaultConnectTimeout",
               (new StringBuilder()).append("").append(timeout).toString());
         properties.put("sun.net.client.defaultReadTimeout",
               (new StringBuilder()).append("").append(timeout).toString());
         System.setProperties(properties);
      }
   }
   
   public static void setProxy(String proxyHost, String proxyPort) {
      if (proxyHost != null && proxyPort != null) {
         Properties properties1 = System.getProperties();
         properties1.put("proxySet", "true");
         properties1.put("proxyHost", proxyHost);
         properties1.put("proxyPort", proxyPort);
         System.setProperties(properties1);
      }
   }
   
   public static String getHostInfo(String s) {
      String s1 = s;
      int i = s1.indexOf("://");
      if (i > 0)
         s1 = s1.substring(i + 3);
      i = s1.indexOf("/");
      if (i > 0)
         s1 = s1.substring(0, i);
      i = s1.indexOf("?");
      if (i > 0)
         s1 = s1.substring(0, i);
      i = s1.indexOf("#");
      if (i > 0)
         s1 = s1.substring(0, i);
      i = s1.indexOf(";");
      if (i > 0)
         s1 = s1.substring(0, i);
      return s1;
   }
   
   public static void rewriteHeaders(Map<String, List<String>> map,
         HttpServletResponse response) {
      if (map != null) {
         Set<String> set = map.keySet();
         Iterator<String> iterator = set.iterator();
         do {
            if (!iterator.hasNext())
               break;
            String s = (String) iterator.next();
            if (s != null && !s.equals("Content-Type")) {
               List<String> list = (List<String>) map.get(s);
               String s1 = "";
               for (Iterator<String> iterator1 = list.iterator(); iterator1.hasNext();) {
                  if (s1.length() > 0)
                     s1 = (new StringBuilder()).append(s1).append(",")
                           .toString();
                  s1 = (new StringBuilder()).append(s1)
                        .append((String) iterator1.next()).toString();
               }

               response.setHeader(s, s1);
            }
         } while (true);
      }
   }
   
   public static void sendError(HttpServletResponse response,
         Integer errorCode, String message) throws IOException {
      if (errorCode != null && errorCode > 0) {
         response.sendError(errorCode, message);
      }
      else {
         response.sendError(503, message);
      }
   }
   
   public static String rewriteEncoding(String s, String s1) {
      if (s.indexOf("charset") < 0)
         return (new StringBuilder()).append(s).append(";charset=").append(s1)
               .toString();
      int i = s.indexOf(";");
      if (i < 0) {
         i = s.indexOf("charset");
      }
      return (new StringBuilder()).append(s.substring(0, i))
            .append(";charset=").append(s1).toString();
   }
   
   public static String getMessage(String uri, Exception exception) {
      String s1 = exception.getClass().getName();
      int i = s1.lastIndexOf('.');
      s1 = s1.substring(i + 1);
      StringWriter stringwriter = new StringWriter();
      PrintWriter printwriter = new PrintWriter(stringwriter);
      exception.printStackTrace(printwriter);
      return new StringBuilder()
         .append("Request: ").append(uri)
         .append("\nException: ")
         .append(s1).append(": ")
         .append(exception.getMessage())
         .append("\n")
         .append(stringwriter.getBuffer().toString()).toString();
   }
}
